package com.ljtxxhwj.myblob.controller;

import com.ljtxxhwj.myblob.entity.Article;
import com.ljtxxhwj.myblob.entity.Like;
import com.ljtxxhwj.myblob.entity.User;
import com.ljtxxhwj.myblob.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/likes")
public class LikeController {

    private final LikeService likeService;

    @Autowired
    public LikeController(LikeService likeService) {
        this.likeService = likeService;
    }

    @GetMapping("/getLiked.do")
    public List<Like> getLiked(@RequestParam("userId") Integer userId) {
        return likeService.selectLiked(userId);
    }


    // 根据用户ID查询该用户点赞的所有文章
    @GetMapping("/getLikesByUserId.do")
    public List<Like> getLikesByUserId(Integer userId) {
        return likeService.selectLikesByUserId(userId);
    }
    @GetMapping("/getTotalLikesByUserId.do")
    public int getTotalLikesByUserId(int userId) {
        // 调用Service层的方法来获取点赞总数
        return likeService.getTotalLikesByUserId(userId);
    }
    // 根据文章ID查询点赞该文章的所有用户
    @GetMapping("/selectLikedArticlesByUserId.do")
    public List<Article> getLikedArticlesByUserId(int userId) {
        return likeService.selectLikedArticlesByUserId(userId);
    }
    @GetMapping("/article/{articleId}.do")
    public List<Like> getLikesByArticleId(@PathVariable Integer articleId) {
        return likeService.selectLikesByArticleId(articleId);
    }

    // 插入一个新的点赞记录
    @PostMapping("/{articleId}/user/{userId}.do")
    public ResponseEntity<String> insertLike(@PathVariable Integer articleId, @PathVariable Integer userId) {
        Like like = new Like();
        like.setArticleId(articleId);
        like.setUserId(userId);
//        like.setLikeDate(LocalDateTime.now());
        like.setLikeDate(new Timestamp(new Date().getTime()));
        try {
            likeService.insertLike(like);
            return new ResponseEntity<>("Like inserted successfully", HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity<>("Error inserting like", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 根据文章ID和用户ID删除点赞记录
    @DeleteMapping("/{articleId}/user/{userId}.do")
    public ResponseEntity<String> deleteLikeByArticleAndUser(@PathVariable Integer articleId, @PathVariable Integer userId) {
        try {
            likeService.deleteLikeByArticleAndUser(articleId, userId);
            return new ResponseEntity<>("Like deleted successfully", HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>("Error deleting like", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}